// app.js
import {getOpenid,getUser,addUser,UdpUser} from './api/api.js'
App({
  onLaunch() {
   this. getUserInfo()
  },
  //授权登录
  getUserInfo(){
    wx.getUserInfo({
      success:res=>{
        wx.setStorageSync('en', res.encryptedData)
        wx.setStorageSync('iv', res.iv)
        wx.login({
          success:res1=>{
            getOpenid(res1.code).then(res2=>{
              wx.setStorageSync('openid',res2.data.openid)
              wx.setStorageSync('session_key',res2.data.session_key)
              wx.setStorageSync('unionid',res2.data.unionid)
              this.getUser()
            })
          }
        })
      }
    })
  },

  // 获取用户
  getUser(){
    const openid = wx.getStorageSync('openid')
    getUser(openid).then(res=>{
      console.log(res);
      if(res.data.data.length === 0){
        addUser(openid).then(res=>{
          console.log('添加成功');
        })
        
      }else{
        UdpUser(res.data.data[0]._id,res.data.data[0].visit_count).then(res=>{
          console.log('修改成功');
        }).catch(err=>{
          // console.log(err);
        })
        
      }
    })
  },

})
